//==========websocket
(function($) {
    $.websocket = function(server,options) {
        var defaults = {
            server: top.location.hostname,
        };
        var opts = $.extend(defaults,options);
        var socket = null;
        var bOpen = false;
        var t1 = 0; 
        var t2 = 0; 
        var loadIndex = 0;
        var messageevent = {
            onInit:function(){
                if(!("WebSocket" in window) && !("MozWebSocket" in window)){  
                    return false;
                }
                if(("MozWebSocket" in window)){
                    socket = new MozWebSocket(server);  
                }else{
                    socket = new WebSocket(server);
                }
                if(opts.onInit){
                    opts.onInit();
                }
            },
            onOpen:function(event){
                bOpen = true;
                if(opts.onOpen){
                    opts.onOpen(event);
                }
            },
            onSend:function(msg){
                t1 = new Date().getTime(); 
                if(opts.onSend){
                    opts.onSend(msg);
                }
                socket.send(msg);
            },
            onMessage:function(msg){
                var data = msg.data;
                if(data !== '成功' && (data).indexOf('心跳消息') == -1 ){
                    data = JSON.parse(data);
                    t2 = new Date().getTime(); 
                    if(opts.onMessage){
                        opts.onMessage(data,t2 - t1)
                    }
                    setTimeout(function(){
                        if(socket.onMessage){
                            socket.onMessage(data,t2 - t1)
                        }
                    },100)
                }
            },
            onError:function(event){
                if(opts.onError){
                    opts.onError(event);
                }
            },
            onClose:function(event){
                if(opts.onclose){
                    opts.onclose(event);
                }
                if(loadIndex < 1000){
                    loadIndex++;
                    setTimeout(function(){ init(); },1000)  
                }
            }
        }

        var init = function(){
            messageevent.onInit();
            socket.onopen = messageevent.onOpen;
            socket.onmessage = messageevent.onMessage;
            socket.onerror = messageevent.onError;
            socket.onclose = messageevent.onClose;
            socket.send = function(pData){
                if(bOpen == false){
                    return false;
                }
                messageevent.onSend(pData);
                return true;
            }
            socket.close = function(){
                messageevent.onClose();
            }
            return socket;
        }

        return init();
    };
})(jQuery);